package viewer;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.TimerTask;

import javax.swing.JFrame;
import javax.swing.JLabel;

import mainBoerse.AccountManagerImpl;
import mainBoerse.Share;
import mainBoerse.UpdateTimer;
import stockPrice.RandomStockPriceProvider;
import stockPrice.StockPriceProvider;

@SuppressWarnings("serial")
public class Viewer extends JFrame {

	private static final int TICK_PERIOD = 1000;
	private UpdateTimer ticker;
	private JLabel clockLabel;
	private static StockPriceProvider provider;
	private AccountManagerImpl impl;
	private ResourceBundle prop;
	
	Timestamp stamp;  
	private class TickerTask extends TimerTask {

		public void run() {
			getProvider().startUpdate();
			String output = createText();
			clockLabel.setText(output);
			clockLabel.repaint();
			provider.startUpdate();
		}

		private String createText() {
			String output = "<html><body>";
			stamp = new Timestamp(System.currentTimeMillis());
			String date = new java.text.SimpleDateFormat(prop.getString("time")).format(stamp);
			output += date + "<br />";
			output += getCourses();
			output += impl.getAllSharesAndCoursesOfAllPlayersToString(prop);			
			output += "</body></html>";
			return output;
		}

		private String getCourses() {
			ArrayList<Share> shares = provider.getAllSharesAsSnapShot();
			StringBuilder builder = new StringBuilder();
			for (Share share : shares) {
				builder.append(share.getAktienName());
				builder.append("<br>");
				builder.append(share.getAktienKurs());
				builder.append(" " +prop.getString("currency"));
				builder.append("<br><br>");
			}
			return builder.toString();
		}
	}

	public Viewer(StockPriceProvider provider, AccountManagerImpl impl, ResourceBundle prop) {
		clockLabel = new JLabel("coming soon ...");
		add("Center", clockLabel);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setSize(180, 360);
		setVisible(true);
		Viewer.provider = provider;
		this.impl = impl;
		this.prop = prop;
	}

	public static StockPriceProvider getProvider() {
		return provider;
	}

	public void start() throws Exception {
		ticker = UpdateTimer.getInstance(); // as daemon
		UpdateTimer.startTimingWithOwnTimerTask(new TickerTask(), 1000, TICK_PERIOD);
		

	}

}